<?php

namespace Modules\AuthAdmin\Models;
use Modules\AuthAdmin\Services\QueryService;
use Illuminate\Support\Facades\DB;
class AuthArea extends BaseApiModel
{
	/**
     * @name   显示状态:0=隐藏,1=显示,0和1修改为true或false
     * @param  int  $value
     * @return Boolean 
     */
    public function getStatusAttribute($value)
    {
        return $value==1?true:false;
    }
	/**
     * @name   更新时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getUpdatedAtAttribute($value)
    {
        return $value?$value:'';
    }
	/**
	 * @name  列表数据
	 * @return json 
	 */
    public function list_data($data){
		$model = $this->query();
		$model = (new QueryService())->query_condition($model,$data,'name');	
        $list = $model->where(['pid'=>$data['pid'],'level_type'=>$data['level_type']])
				->orderBy('id','desc')
				->paginate($data['pagesize'])
				->toArray(); 
		return $this->api_success(['data'=>[
			'list'=>$list['data'],
			'total'=>$list['total']
		]]);		
	}
	/**
	 * @name  导入服务器数据
	 */
    public function import_data()
    {
		if($this->count()){
			return $this->api_error(['msg'=>'已有数据！']);
		}
		header("Content-type:text/html;charset=utf-8");
		require base_path('Modules/AuthAdmin/Services/lib/PHPExcel').'/Classes/PHPExcel/IOFactory.php';
		$input_file_name = public_path('upload/area').'/省市区数据.xls';
        if (!file_exists($input_file_name)) {
            return $this->api_error(['msg'=>'数据文件不存在！']);
        }
		date_default_timezone_set('PRC');
		try {
			$input_file_type = \PHPExcel_IOFactory::identify($input_file_name);
			$obj_reader = \PHPExcel_IOFactory::createReader($input_file_type);
			$obj_php_excel = $obj_reader->load($input_file_name);
		} catch(Exception $e) {
			return $this->api_error(['msg'=>'加载文件发生错误！']);
		}
		$obj_php_excel = \PHPExcel_IOFactory::load($input_file_name);
		$sheet = $obj_php_excel->getSheet(0)->toArray();
		DB::beginTransaction();
		try{
			foreach($sheet as $k=>$v){
				if($k!=0){
					$v = [
						$sheet[0][0]=> $v[0],
						$sheet[0][1]=> $v[1],
						$sheet[0][2]=> $v[2],
						$sheet[0][3]=> $v[3],
						$sheet[0][4]=> $v[4],
						$sheet[0][5]=> $v[5],
						$sheet[0][6]=> $v[6],
						$sheet[0][7]=> $v[7],
						$sheet[0][8]=> $v[8],
						$sheet[0][9]=> $v[9],
						$sheet[0][10]=> $v[10],
						$sheet[0][11]=> $v[11],
					];
					if(!$v['city_code']){
						unset($v['city_code']);
					}
					if(!$v['zip_code']){
						unset($v['zip_code']);
					}
					$this->insert($v);
				}
			}
		 DB::commit();
		}catch(\Exception $e){
			DB::rollBack();	 
			return $this->api_error(['msg'=>'导入数据失败！']);
		}	
		return $this->api_success(['msg'=>'导入数据成功！']);
    }
}
